package com.ruoyi.mp.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.PageUtil;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.mp.domain.MpMaterial;import com.ruoyi.mp.service.IMpMaterialService;
import com.ruoyi.mp.util.MapUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.draft.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/mp/draft")
@Validated
@Slf4j
public class MpDraftController extends BaseController {

    @Resource
    private IMpMaterialService mpMaterialService;

    @Autowired
    private WxMpService wxMpService;

    /**
     * 获得草稿分页
     ** @return
     */
    @GetMapping("/page")
    @SaCheckPermission("mp:draft:query")
    public TableDataInfo getDraftPage(PageQuery pageQuery) {
        // 从公众号查询草稿箱
        WxMpDraftList draftList;
        Integer pageNum = pageQuery.getPageNum();
        Integer pageSize = pageQuery.getPageSize();
        int offset = PageUtil.getStart(pageNum - 1, pageSize);
        try {
            draftList = wxMpService.getDraftService().listDraft(offset, pageSize);
        } catch (WxErrorException e) {
            log.error("获取草稿失败 => {}", e.getMessage());
            throw new ServiceException("获取草稿失败|"+e.getMessage());
        }
        // 查询对应的图片地址。目的：解决公众号的图片链接无法在我们后台展示
        setDraftThumbUrl(draftList.getItems());

        // 返回分页
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(draftList.getItems());
        tableDataInfo.setTotal(draftList.getTotalCount());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        return tableDataInfo;
    }

    private void setDraftThumbUrl(List<WxMpDraftItem> items) {
        // 1.1 获得 mediaId 数组
        Set<String> mediaIds = new HashSet<>();
        items.forEach(item -> item.getContent().getNewsItem().forEach(newsItem -> mediaIds.add(newsItem.getThumbMediaId())));
        if (CollUtil.isEmpty(mediaIds)) {
            return;
        }
        // 1.2 批量查询对应的 Media 素材
        Map<String, MpMaterial> materials = IterUtil.toMap(mpMaterialService.getMaterialListByMediaId(mediaIds),
            MpMaterial::getMediaId);

        // 2. 设置回 WxMpDraftItem 记录
        items.forEach(item -> item.getContent().getNewsItem().forEach(newsItem ->
            MapUtils.findAndThen(materials, newsItem.getThumbMediaId(), material -> newsItem.setThumbUrl(material.getUrl()))));
    }

    /**
     * 创建草稿
     *
     * @param draft
     * @return
     */
    @PostMapping("/create")
    @SaCheckPermission("mp:draft:edit")
    public R<String> deleteDraft(@RequestBody WxMpAddDraft draft) {
        try {
            String mediaId = wxMpService.getDraftService().addDraft(draft);
            return R.ok("ok", mediaId);
        } catch (WxErrorException e) {
            log.error("创建草稿失败 => {}", e.getMessage());
            throw new ServiceException("创建草稿失败");
        }
    }

    /**
     * 更新草稿
     *
     * @param mediaId
     * @param articles
     * @return
     */
    @PutMapping("/update")
    @SaCheckPermission("mp:draft:edit")
    public R<Void> updateDraft(
        @RequestParam("mediaId") String mediaId,
        @RequestBody List<WxMpDraftArticles> articles) {
        try {
            for (int i = 0; i < articles.size(); i++) {
                WxMpDraftArticles article = articles.get(i);
                wxMpService.getDraftService().updateDraft(new WxMpUpdateDraft(mediaId, i, article));
            }
            return R.ok();
        } catch (WxErrorException e) {
            log.error("更新草稿失败 => {}", e.getMessage());
            throw new ServiceException("更新草稿失败");
        }
    }

    /**
     * 删除草稿
     *
     * @param mediaId
     * @return
     */
    @DeleteMapping("/delete")
    @SaCheckPermission("mp:draft:edit")
    public R<Void> deleteDraft(@RequestParam("mediaId") String mediaId) {
        try {
            wxMpService.getDraftService().delDraft(mediaId);
            return R.ok();
        } catch (WxErrorException e) {
            log.error("删除草稿失败 => {}", e.getMessage());
            throw new ServiceException("删除草稿失败");
        }
    }

}
